<template>
  <div class="container">
    <div class="app-container">
      <el-tree default-expand-all :data="list" :props="defaultProps">
        <template #default="{ data }">
          <el-row style="width: 100%">
            <el-col :span="20">{{ data.name }}</el-col>
            <el-col :span="4">
              <el-row>
                <el-col :span="8">{{ data.managerName }}</el-col>
                <el-col :span="16">
                  <el-dropdown @click.native.stop @command="dropdownClick($event, data)">
                    <span class="el-dropdown-link">
                      操作<i class="el-icon-arrow-down el-icon--right" />
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          command="add"
                        >添加子部门</el-dropdown-item>
                        <el-dropdown-item
                          command="edit"
                        >编辑部门</el-dropdown-item>
                        <el-dropdown-item command="del">删除</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-tree>
    </div>
    <!-- 编辑部门 -->
    <el-dialog
      title="编辑子部门"
      :visible.sync="editDialogVisible.isShowDialog"
      width="30%"
    >
      <el-form ref="refEditDialog" label-width="120px" :model="editDialogVisible.data" :rules="editDialogVisible.rules">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="editDialogVisible.data.name" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="editDialogVisible.data.code" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select v-model="editDialogVisible.data.managerId" style="width:100%" @visible-change="editDialogVisible.methods.onVisibleChangeOfManager">
            <el-option
              v-for="v of editDialogVisible.managerIdList"
              :key="v.id"
              :label="v.username"
              :value="v.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="editDialogVisible.data.introduce" type="textarea" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="editDialogVisible.methods.okDialog">确定</el-button>
          <el-button @click="editDialogVisible.isShowDialog=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 添加部门 -->
    <el-dialog
      title="添加子部门"
      :visible.sync="dialogVisible.isShowDialog"
      width="30%"
    >
      <el-form ref="refFormDialog" label-width="120px" :model="dialogVisible.data" :rules="dialogVisible.rules">
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="dialogVisible.data.name" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input v-model="dialogVisible.data.code" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="managerId">
          <el-select v-model="dialogVisible.data.managerId" style="width:100%" @visible-change="dialogVisible.methods.onVisibleChangeOfManager">
            <el-option
              v-for="v of dialogVisible.managerIdList"
              :key="v.id"
              :label="v.username"
              :value="v.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input v-model="dialogVisible.data.introduce" type="textarea" placeholder="2-10个字符" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="dialogVisible.methods.okDialog">确定</el-button>
          <el-button @click="dialogVisible.isShowDialog=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getDepartment, getSimple, addDeptDialog, getDepartmentDetail, editDepartment, delDepartment } from '@/api/department'

export default {
  name: 'Department',
  data() {
    return {
      list: [],
      editDialogVisible: {
        isShowDialog: false,
        managerIdList: [],
        data: {
          code: '',
          introduce: '',
          managerId: '',
          name: '',
          pid: '', // 父部门的id
          id: '',
          createTime: ''
        },
        rules: Object.seal({
          name: [{ required: true, message: '部门名称不能为空' }, { min: 2, max: 10, message: '长度在2-10个字符' }, {
            validator: async(rule, value, callback) => {
              const res = await getDepartment()
              console.log(res, '12132113131313121231313')
              if (res.filter(v => v.id !== this.editDialogVisible.data.id).some(v => v.name === value)) {
                callback(new Error('该部门已存在'))
              } else {
                callback()
              }
            }
          }],
          code: [{ required: true, message: '部门编码不能为空' }, { min: 2, max: 10, message: '长度在2-10个字符' }, {
            validator: async(rule, value, callback) => {
              const res = await getDepartment()
              if (res.filter(v => v.id !== this.editDialogVisible.data.id).some(v => v.code === value)) {
                callback(new Error('该部门编码已存在'))
              } else {
                callback()
              }
            }
          }],
          managerId: [{ required: true, message: '部门负责人不能为空' }],
          introduce: [{ required: true, message: '部门介绍不能为空' }, { min: 1, max: 100, message: '长度在1-100个字符' }]
        }),
        methods: {
          del: async(id) => {
            await delDepartment(id)
            this.$message.success('删除成功')
            this.getDepartment()
          },
          open: async(data) => {
                    this.$refs.refEditDialog?.resetFields()
                    const departmentDetail = await getDepartmentDetail(data.id)
                    console.log(departmentDetail)
                    this.editDialogVisible.data = departmentDetail

                    const res = await getSimple()
                    console.log(res)
                    this.editDialogVisible.managerIdList = res

                    this.editDialogVisible.isShowDialog = true
          },
          onVisibleChangeOfManager: (visible) => {
            if (!visible) {
              this.$refs.refEditDialog.validateField('managerId')
            }
          },
          okDialog: async() => {
            this.$refs.refEditDialog.validate()
            await editDepartment(this.editDialogVisible.data)
            this.$message.success('修改成功')
            this.editDialogVisible.isShowDialog = false
            this.getDepartment()
          }
        }
      },
      dialogVisible: {
        isShowDialog: false,
        managerIdList: [],
        data: {
          code: '',
          introduce: '',
          managerId: '',
          name: '',
          pid: ''
        },
        rules: Object.seal({
          name: [{ required: true, message: '部门名称不能为空' }, { min: 2, max: 10, message: '长度在2-10个字符' }, {
            async validator(rule, value, callback) {
              const res = await getDepartment()
              if (res.some(v => v.name === value)) {
                callback(new Error('该部门已存在'))
              } else {
                callback()
              }
            }
          }],
          code: [{ required: true, message: '部门编码不能为空' }, { min: 2, max: 10, message: '长度在2-10个字符' }, {
            async validator(rule, value, callback) {
              const res = await getDepartment()
              if (res.some(v => v.code === value)) {
                callback(new Error('该部门编码已存在'))
              } else {
                callback()
              }
            }
          }],
          managerId: [{ required: true, message: '部门负责人不能为空' }],
          introduce: [{ required: true, message: '部门介绍不能为空' }, { min: 1, max: 100, message: '长度在1-100个字符' }]
        }),
        methods: {
          open: async(data) => {
                    this.$refs.refFormDialog?.resetFields()
                    const res = await getSimple()
                    console.log(res)
                    this.dialogVisible.managerIdList = res
                    this.dialogVisible.data.pid = data.id
                    this.dialogVisible.isShowDialog = true
          },
          onVisibleChangeOfManager: (visible) => {
            if (!visible) {
              this.$refs.refFormDialog.validateField('managerId')
            }
          },
          okDialog: async() => {
            this.$refs.refFormDialog.validate()
            await addDeptDialog(this.dialogVisible.data)
            this.$message.success('添加成功')
            this.dialogVisible.isShowDialog = false
            this.getDepartment()
          }
        }
      },
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created() {
    this.getDepartment()
  },
  methods: {
    async dropdownClick(command, data) {
      // console.log(command, data)
      if (command === 'add') {
        await this.dialogVisible.methods.open(data)
      }
      if (command === 'edit') {
        await this.editDialogVisible.methods.open(data)
      }
      if (command === 'del') {
        await this.editDialogVisible.methods.del(data.id)
      }
    },
    async getDepartment() {
      // 获取数据
      const res = await getDepartment()
      console.log(res)

      // 声明一个找儿子的函数
      function getChildren(id) {
        return res.filter((v) => v.pid === id)
      }
      //
      res.forEach((v) => {
        v.children = getChildren(v.id)
      })

      // 将一级节点找出来
      const list = res.filter((v) => v.pid === 0)
      // console.log(list, 'list')
      this.list = list
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  padding: 30px 140px;
  font-size: 14px;
}
</style>
